<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <canvas class="canvas" width="500" height="500"></canvas>
  <!-- 顶点着色器 -->
  <script id="vertex-shader" type="x-shader/x-vertex">
    attribute vec4 aPos;
    uniform mat4 uTranslate;
    void main() {
      gl_Position = uTranslate * aPos;
      gl_PointSize = 10.0;
    }
  </script>
  <!-- 片段着色器 -->
  <script id="fragment-shader" type="x-shader/x-fragment">
    precision mediump float;
    uniform vec4 uColor;
    void main() {
      gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    } 
  </script>
  <script type="module">
    import initShader from "./utils/initShader.js";
    import { mat4 } from "./utils/gl-matrix/esm/index.js";
    const canvas = document.querySelector(".canvas");
    const gl = canvas.getContext("webgl");
    const program = initShader(gl);

    const vertices = new Float32Array([        
      -0.5, -0.5,
      0.5, -0.5,
      0.0, 0.5
    ])

    // 缓冲区
    const buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

    const posLocation = gl.getAttribLocation(program, "aPos");

    gl.vertexAttribPointer(
      posLocation,
      2,
      gl.FLOAT,  
      false,
      2 * Float32Array.BYTES_PER_ELEMENT,
      0
    )

    gl.enableVertexAttribArray(posLocation);


    const uTranslateLocation = gl.getUniformLocation(program, "uTranslate");

    // 创建4*4的单位矩阵
    const matrix = mat4.create();
    // 平移
    // mat4.translate(matrix, matrix, [0.5, 0.5, 0.0]);
    mat4.fromTranslation(matrix, [0.5, 0.2, 0.0]);

    gl.uniformMatrix4fv(uTranslateLocation, false, matrix);

    gl.drawArrays(gl.TRIANGLES, 0, 3);
  </script>
</body>
</html>